package com.bsoft.gol.hcs.specialist.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import ctd.controller.exception.ControllerException;
import ctd.net.rpc.Client;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.BeanUtils;
import ctd.util.JSONUtils;
import ctd.util.annotation.RpcService;
import com.bsoft.gol.hcs.enumcase.FollowUpSubsmoduleEnum;
import com.bsoft.gol.hcs.enumcase.SubscribeTypeEnum;
import com.bsoft.gol.hcs.followup.dao.FusAfterHosRecordDAO;
import hcn.base.Dept;
import hcn.base.Organization;
import hcn.base.healthinfo.vo.NewReplyListVO;
import hcn.bean.specialist.vo.QueryDoctorDepartmentListResponse;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.atag.dao.model.SimplePageInfo;
import hcn.docteam.DocTeamMemberEntity;
import hcn.util.ResultCode;
import com.bsoft.gol.hcs.odshmrecord.bean.response.OdsHmAbnormal;
import com.bsoft.gol.hcs.odshmrecord.dao.OdsHmDiseaseRelationDAO;
import org.atag.util.common.SpringPropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.atag.dao.model.PageQo;
import pcn.vo.consultation.QueryDoctorFollowupVo;
import service.rpc.*;
import com.bsoft.gol.hcs.specialist.bean.request.*;
import com.bsoft.gol.hcs.specialist.bean.response.*;
import com.bsoft.gol.hcs.specialist.bean.vo.FollowUpRecordsVO;
import com.bsoft.gol.hcs.specialist.dao.*;
import com.bsoft.gol.hcs.specialist.entity.*;
import com.bsoft.gol.hcs.specialist.service.IFollowUpPlanService;
import com.bsoft.gol.hcs.specialist.service.IFusHealthEducationService;
import com.bsoft.gol.hcs.utils.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@SsdevService("patientFollowup")
public class PatientFollowupService {
    private final static Logger logger = LoggerFactory.getLogger(PatientFollowupService.class);

    @Autowired
    private FollowUpRecordsDAO followUpRecordsDAO;
    @Autowired
    private FollowUpSubsmoduleDao followUpSubsmoduleDao;
    @Autowired
    private DoctorInfoServiceIntf doctorInfoRpcService;
    @Autowired
    private PatientSearchRuleDAO patientSearchRuleDAO;
    @Autowired
    private IOrganizationRpcService organizationRpcService;
    @Autowired
    private IDeptMainRpcService deptMainRpcService;
    @Autowired
    private IHealthInfoRpcService healthInfoRpcService;
    @Autowired
    private FollowUpRecordsContentDAO followUpRecordsContentDAO;
    @Autowired
    private OdsHmDiseaseRelationDAO odsHmDiseaseRelationDAO;
    @Autowired
    private FollowUpRouteDetailFormDAO followUpRouteDetailFormDAO;
    @Resource(name = "followUpPlanService")
    private IFollowUpPlanService followUpPlanService;
    @Value("${project_source}")
    private String projectSource;
    @Autowired
    private IDocTeamRpcService docTeamRpcService;
    @Autowired
    private IDocTeamMemberRpcService docTeamMemberRpcService;
    @Autowired
    private FollowUpRecordsEducationDAO followUpRecordsEducationDAO;
    @Autowired
    private FollowUpRecordsRequisitionDAO followUpRecordsRequisitionDAO;
    @Autowired
    private FollowUpRecordsExtendDAO followUpRecordsExtendDAO;
    @Autowired
    private FusAfterHosRecordDAO fusAfterHosRecordDAO;
    @Autowired
    private FusAfterHealthEducationDAO fusAfterHealthEducationDAO;
    @Autowired
    private FusAfterHosRecordContentDAO fusAfterHosRecordContentDAO;
    @Autowired
    private FusAfterRequisitionRecordDAO fusAfterRequisitionRecordDAO;
    @Autowired
    private FusAfterRecommendDeptDAO fusAfterRecommendDeptDAO;
    @Autowired
    private IFusHealthEducationService fusHealthEducationService;
    @Autowired
    private DocTeamDiseaseDAO docTeamDiseaseDAO;

    /**
     * 居民-我的专科随访计划
     *
     * @param request
     * @return
     */
    @RpcService
    public QueryPlanListResponse queryPlanList(QueryPlanListRequest request) throws ControllerException {
        QueryPlanListResponse response = new QueryPlanListResponse();
        String today = DateUtils.dateFormate(new Date(), "yyyy-MM-dd");
        if (CommonUtils.isEmpty(request.getCardType()) || CommonUtils.isEmpty(request.getCardNumber())) {
            throw new ControllerException(ResultCode.ERROR, "入参不能为空");
        }

        List<FollowUpRecords> followUpRecordList = followUpRecordsDAO.queryFollowUpRecordsByPerson(request.getCardType(), request.getCardNumber(), 0, 1);
        if (followUpRecordList != null && followUpRecordList.size() > 0) {
            BeanUtils.copy(followUpRecordList.get(0), response);
        }
        List<FollowUpRecords> dateGroupList = followUpRecordsDAO.queryDateGroupList(request.getCardType(), request.getCardNumber(), today);
        if (CommonUtils.isEmpty(dateGroupList)) {
            return response;
        }
        List<QueryPlanListResponse.dateGroup> resDateGroupList = Lists.newArrayList();
        for (FollowUpRecords followUpRecords : dateGroupList) {
            QueryPlanListResponse.dateGroup resDateGroup = new QueryPlanListResponse.dateGroup();
            resDateGroup.setPlanDate(followUpRecords.getPlanTime());
            resDateGroupList.add(resDateGroup);
            List<QueryPlanListResponse.FollowUpDatePlan> resFollowUpDatePlanList = followUpRecordsDAO.queryPlanList(request.getCardType(), request.getCardNumber(), followUpRecords.getPlanTime(), today);
            if (CommonUtils.isEmpty(resFollowUpDatePlanList)) {
                continue;
            }
            for (QueryPlanListResponse.FollowUpDatePlan followUpDatePlan : resFollowUpDatePlanList) {
                Organization organization = organizationRpcService.getOrgDetailByOrgCode(followUpDatePlan.getOrganizationId());
                if (organization != null) {
                    followUpDatePlan.setOrgId(organization.getOrgId());
                    followUpDatePlan.setOrganizationName(organization.getFullName());
                    Dept dept = deptMainRpcService.getDeptByLocalDeptId(organization.getOrgId(), followUpDatePlan.getDepartmentId());
                    if (dept != null) {
                        followUpDatePlan.setDeptId(dept.getDeptId());
                    }
                }

                //问卷都在这个表里面follow_up_records_requisition
                List<FollowUpRecordsRequisition> followUpRecordsRequisitions = followUpRecordsRequisitionDAO.findQuestionByRecordId(followUpDatePlan.getRecordId());
                //返回问卷集合
                QueryPlanListResponse.InnerMedicalRecord innerMedicalRecord= null;
                if(CommonUtils.isNotEmpty(followUpRecordsRequisitions)){
                    List<QueryPlanListResponse.InnerMedicalRecord> questionnaireList = new ArrayList<>();
                    followUpDatePlan.setQuestionnaireList(questionnaireList);

                    for (FollowUpRecordsRequisition followUpRecordsRequisition : followUpRecordsRequisitions) {
                        if(CommonUtils.isNotEmpty(followUpRecordsRequisition)){
                            //问卷填写了的也要返回-填写了也要查看的--by tongtp 20230203
                            if (CommonUtils.isNotEmpty(followUpRecordsRequisition.getQuestionnaireId())) {
                                innerMedicalRecord = new QueryPlanListResponse.InnerMedicalRecord();
                                innerMedicalRecord.setQuestionnaireId(followUpRecordsRequisition.getQuestionnaireId());
                                String questionnaireName = followUpRecordsRequisition.getQuestionnaireName();
                                if (CommonUtils.isNotEmpty(questionnaireName)) {
                                    questionnaireName =
                                            questionnaireName.replace("<p>", "").replace("</p>", "").replace("<br>",
                                                    "");
                                }
                                innerMedicalRecord.setQuestionnaireName(questionnaireName);
                                innerMedicalRecord.setUserInfoId(followUpRecordsRequisition.getUserInfoId());
                                innerMedicalRecord.setFormId(followUpRecordsRequisition.getFormId());
                                questionnaireList.add(innerMedicalRecord);
                            }
                        }
                    }
                }

                List<FollowUpRecordsContent> follows = new ArrayList<>();
                followUpDatePlan.setFollowUpPlanList(follows);


                //健康宣教都在这张表里面follow_up_records_education
                List<FollowUpRecordsEducation> followUpRecordsEducationList = followUpRecordsEducationDAO.findQuestionByRecordId(followUpDatePlan.getRecordId());
                if (CommonUtils.isNotEmpty(followUpRecordsEducationList)){

                    for (FollowUpRecordsEducation followUpRecordsEducation : followUpRecordsEducationList) {
                        FollowUpRecordsContent recordsContent = new FollowUpRecordsContent();
                        recordsContent.setEducationId(followUpRecordsEducation.getEducationId());
                        recordsContent.setEducationName(followUpRecordsEducation.getEducationName());
                        recordsContent.setEducationStatus(followUpRecordsEducation.getEducationStatus());
                        follows.add(recordsContent);
                    }
                }

//                //健康监测都在这张表里面follow_up_records_extend
//                List<FollowUpRecordsExtendEntity> recordsExtendEntityList = followUpRecordsExtendDAO.findFollowUpRecordsExtendEntityByRecordId(followUpDatePlan.getRecordId());
//                if (CommonUtils.isNotEmpty(recordsExtendEntityList)){
//                    FollowUpRecordsContent recordsContent = null;
//                    for (FollowUpRecordsExtendEntity followUpRecordsExtendEntity : recordsExtendEntityList) {
//                        recordsContent = new FollowUpRecordsContent();
//                        recordsContent.setIndexClassifyId(followUpRecordsExtendEntity.getMonitorId());
//                        recordsContent.setIndexClassifyName(followUpRecordsExtendEntity.getMonitorName());
//                        follows.add(recordsContent);
//                    }
//                }

                //查询其他的随访内容
                List<FollowUpRecordsContent> followUpRecordsContentList = followUpRecordsContentDAO.queryContentByRecordId(followUpDatePlan.getRecordId());
                List<FollowUpRecordsContent> contents = followUpRecordsContentList.stream().filter(t -> CommonUtils.isEmpty(t.getQuestionnaireId()) && CommonUtils.isEmpty(t.getQuestionnaireId())).collect(Collectors.toList());
                if (CommonUtils.isNotEmpty(contents)){
                    follows.addAll(contents);
                }


                //返回推荐科室
                if (CommonUtils.isNotEmpty(followUpDatePlan.getRouteId()) && CommonUtils.isNotEmpty(followUpDatePlan.getRouteDetailId())) {
                    List<FollowUpRouteDetailForm> followUpRouteDetailForms = followUpRouteDetailFormDAO.queryByRouteDetailId(followUpDatePlan.getRouteDetailId());
                    if(CommonUtils.isNotEmpty(followUpRouteDetailForms)){
                        List<FollowUpRouteDetailRecommendDeptReq> recommendDept = new ArrayList<>();
                        followUpDatePlan.setRecommendDept(recommendDept);

                        FollowUpRouteDetailRecommendDeptReq followUpRouteDetailRecommendDeptReq = null;

                        for (FollowUpRouteDetailForm followUpRouteDetailForm : followUpRouteDetailForms) {
                            if(CommonUtils.isNotEmpty(followUpRouteDetailForm.getDeptCode())){
                                followUpRouteDetailRecommendDeptReq = new FollowUpRouteDetailRecommendDeptReq();
                                followUpRouteDetailRecommendDeptReq.setFactorType((byte)0);
                                followUpRouteDetailRecommendDeptReq.setParentDepartmentName(followUpRouteDetailForm.getParentDeptName());
                                followUpRouteDetailRecommendDeptReq.setDepartmentName(followUpRouteDetailForm.getDeptName());
                                followUpRouteDetailRecommendDeptReq.setParentDepartmentCode(followUpRouteDetailForm.getParentDeptCode());
                                followUpRouteDetailRecommendDeptReq.setDepartmentCode(followUpRouteDetailForm.getDeptCode());
                                recommendDept.add(followUpRouteDetailRecommendDeptReq);
                            }
                        }
                    }
//                    followUpDatePlan.setFollowUpRouteDetailForms(followUpRouteDetailForms);
                }
                resDateGroup.setFollowUpDatePlanList(resFollowUpDatePlanList);
            }
        }
        response.setDateGroupList(resDateGroupList);
        return response;
    }

    @RpcService
    public List<QueryDoctorListResponse> queryDoctorList(QueryPlanListRequest request) throws ControllerException {
        List<QueryDoctorListResponse> returnList = null;
        //查询团队、机构等信息集合
        List<QueryDoctorListResponse> queryDoctorListResponseList = followUpRecordsDAO.queryDoctorList(request.getCardType(), request.getCardNumber());
        if (CommonUtils.isNotEmpty(queryDoctorListResponseList)) {
            //取出团队id集合
            List<Long> collect = queryDoctorListResponseList.stream().map(c -> c.getMedicalTeamId()).collect(Collectors.toList());
            //查询团队信息集合
            List<DocTeamMemberEntity> docTeamMemberEntities = docTeamMemberRpcService.queryDocTeamMemberListByTeamIdList(collect);
            if(CommonUtils.isNotEmpty(docTeamMemberEntities)){
                returnList = new ArrayList<>();
                QueryDoctorListResponse responseBean;

                //拥有团队成员信息的对象数据赋值
                for (QueryDoctorListResponse queryDoctorListResponse : queryDoctorListResponseList) {
                    for (DocTeamMemberEntity docTeamMemberEntity : docTeamMemberEntities) {
                        if(queryDoctorListResponse.getMedicalTeamId().longValue() == docTeamMemberEntity.getMedicalTeamId()){
                            responseBean = new QueryDoctorListResponse();
                            BeanUtils.copy(queryDoctorListResponse,responseBean);
                            responseBean.setMedicalTeamId(docTeamMemberEntity.getMedicalTeamId());
                            responseBean.setDoctorCode(docTeamMemberEntity.getDoctorCode());
                            responseBean.setDocId(docTeamMemberEntity.getDocId());
                            responseBean.setDoctorId(docTeamMemberEntity.getDoctorId());
                            responseBean.setDoctorName(docTeamMemberEntity.getDoctorName());
                            responseBean.setProfessionalCode(docTeamMemberEntity.getProfessionalCode());
                            responseBean.setProfessionalName(docTeamMemberEntity.getProfessionalName());
                            responseBean.setDepartmentCode(docTeamMemberEntity.getDepartmentCode());
                            responseBean.setDepartmentId(docTeamMemberEntity.getDepartmentId());
                            responseBean.setDepartmentName(docTeamMemberEntity.getDepartmentName());
                            responseBean.setConsultDoctorFlag(false);
                            returnList.add(responseBean);
                        }
                    }

                }

                if(CommonUtils.isNotEmpty(returnList)){
                    for (QueryDoctorListResponse queryDoctorListResponse : returnList) {
                        queryDoctorListResponse.setConsultDoctorFlag(false);
                        Long count = doctorInfoRpcService.queryConsultDoctorCount(queryDoctorListResponse.getDocId());
                        if (null != count && count > Constants.ZORE) {
                            queryDoctorListResponse.setConsultDoctorFlag(true);
                        }
                    }
                }
            }
        }
        return returnList;

    }

    @RpcService
    public QueryPatientFollowupTotalResp queryMyFollowUpTaskTotal(QueryPatientFollowupTotalReq request) throws ControllerException {
        try {
            //查询我的待随访任务总数
            String strToday = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            Date today = new SimpleDateFormat("yyyy-MM-dd").parse(strToday);
            QueryPatientFollowupTotalResp queryPatientFollowupTotalResp = followUpRecordsDAO.queryMyFollowUpTaskTotal(request.getPatientId(), today);
            return queryPatientFollowupTotalResp;
        } catch (Exception e) {
            throw new ControllerException("查询失败，原因:" + e.getMessage());
        }
    }

    @RpcService
    public QueryDoctorFollowupResp queryDoctorFollowupInfo(QueryDoctorFollowupReq request) throws ControllerException {
        QueryDoctorFollowupResp queryDoctorFollowupResp = new QueryDoctorFollowupResp();
        String subScriptionTypestrs = request.getSubScriptionType();
        if (subScriptionTypestrs != null && !subScriptionTypestrs.isEmpty()) {
            Date today = new Date();
            String strToday = DateUtils.dateFormate(today, "yyyy-MM-dd HH:mm:ss");
            String current = DateUtils.dateFormate(today, "yyyy-MM-dd");
            String startDate = DateUtils.dateFormate(DateUtils.dateSub(today, 7), "yyyy-MM-dd HH:mm:ss");

            String[] subScriptonArray = subScriptionTypestrs.split(",");
            for (String subScriptionType : subScriptonArray) {
                //异常提醒
                if (SubscribeTypeEnum.YCTX.getCode().equals(subScriptionType)) {
                    //查询当时时间前一周的数据
                    List<FollowUpRecordsVO> patientInfoList =
                            followUpRecordsDAO.queryAbnormalFollowupList(request.getOrganizationId(),
                                    request.getDocId(), startDate, strToday);
                    if (CommonUtils.isEmpty(patientInfoList)) {
                        patientInfoList = Lists.newArrayList();
                    }

                    List<OdsHmAbnormal> diseaseRelationList =
                            odsHmDiseaseRelationDAO.queryAbnormalList(request.getOrganizationId(), request.getDocId(),
                                    startDate, strToday);
                    if (CommonUtils.isEmpty(diseaseRelationList)) {
                        diseaseRelationList = Lists.newArrayList();
                    }
                    queryDoctorFollowupResp.setUnReadAbnormalTotal(Long.valueOf(patientInfoList.size() + diseaseRelationList.size()));
                    queryDoctorFollowupResp.setTheCriticalValueList(patientInfoList);
                    queryDoctorFollowupResp.setOdsHmDiseaseRelationList(diseaseRelationList);
                }
                //随访任务
                if (SubscribeTypeEnum.SFRW.getCode().equals(subScriptionType)) {
                    List<FollowUpRecordsVO> patientInfoList1=null;
                    List<Long> medicalTeamIdsByDoctorId = null;
                    List<Long> teamIdList = null;
                    List<String> chronicDiseaseId = null;
                    if (CommonUtils.isNotEmpty(request.getDocId())) {
                        medicalTeamIdsByDoctorId = docTeamMemberRpcService.findMedicalTeamIdsByDoctorId(request.getDocId());
                        if (CommonUtils.isNotEmpty(request.getDocId())) {
                            if (CommonUtils.isEmpty(medicalTeamIdsByDoctorId)) {
                                return queryDoctorFollowupResp;
                            }
                            //这里筛选团队必须是专科随访团队
                            teamIdList = docTeamRpcService.queryMedicalTeamId(medicalTeamIdsByDoctorId);
                            if (CommonUtils.isNotEmpty(teamIdList)){
                                //查询该医生拥有的团队下管理的所有病种
                                chronicDiseaseId = docTeamDiseaseDAO.findChronicDiseaseId(teamIdList);
                            }
                            request.setTeamChronicDiseaseIdList(chronicDiseaseId);
                            request.setMedicalTeamId(teamIdList);
                            request.setDocId(null);
                            patientInfoList1 = followUpRecordsDAO.queryToPerformFollowupList(request.getOrganizationId(), request.getDocId(), current, request.getMedicalTeamId(),request.getTeamChronicDiseaseIdList());
                        }
                    }else{
                        patientInfoList1 = followUpRecordsDAO.queryToPerformFollowupList(request.getOrganizationId(), request.getDocId(), current,request.getMedicalTeamId(),request.getTeamChronicDiseaseIdList());
                    }
                    if (CommonUtils.isEmpty(patientInfoList1)) {
                        patientInfoList1 = Lists.newArrayList();
                    } else {
                        //查询随访内容
                        List<Long> recordIds = new ArrayList<>();
                        for (FollowUpRecordsVO followUpRecord : patientInfoList1) {
                            recordIds.add(followUpRecord.getRecordId());
                        }
                        List<FollowUpRecordsContent> followUpRecordsContents =
                                followUpRecordsContentDAO.queryByRecordIds(recordIds);
                        for (FollowUpRecordsVO followUpRecordsVO : patientInfoList1) {
                            List<FollowUpRecordsContent> contentList = new ArrayList<>();
                            followUpRecordsVO.setContentList(contentList);
                            if (CollectionUtils.isEmpty(followUpRecordsContents)) {
                                continue;
                            }
                            for (FollowUpRecordsContent followUpRecordsContent : followUpRecordsContents) {
                                if (followUpRecordsContent.getRecordId().equals(followUpRecordsVO.getRecordId())) {
                                    contentList.add(followUpRecordsContent);
                                }
                            }
                        }
                    }

                    queryDoctorFollowupResp.setOnOutPatientApintmentList(patientInfoList1);
                }
                //入组申请
                if (SubscribeTypeEnum.RZSQ.getCode().equals(subScriptionType)) {
                    List<QueryDoctorFollowupResp.patientInfo> patientInfoList2 = followUpRecordsDAO.queryGroupAuditList(request.getDocId());
                    if (CommonUtils.isEmpty(patientInfoList2)) {
                        patientInfoList2 = Lists.newArrayList();
                    }
                    queryDoctorFollowupResp.setIntoGroupAssessmentList(patientInfoList2);
                }
                //我的诊室RPC 调取pcn-online查询
                if (SubscribeTypeEnum.WDZS.getCode().equals(subScriptionType)) {
                    Organization organization =
                            organizationRpcService.getOrgDetailByOrgCode(request.getOrganizationId());
                    if (CommonUtils.isNotNull(organization)) {
                        List<QueryDoctorFollowupResp.patientInfo> patientInfoList4 = Lists.newArrayList();
                        List<QueryDoctorFollowupVo.patientInfo> patientInfo4 = null;
                        try {
                            patientInfo4 = (List<QueryDoctorFollowupVo.patientInfo>) Client.rpcInvoke("hco.consult",
                                    "queryMyClinicList", organization.getOrgId(), request.getDocId());
                        } catch (Exception e) {
                            logger.info("查询我的诊室失败", e.getMessage());
                        }
                        if (CommonUtils.isNotNull(patientInfo4)) {
                            for (QueryDoctorFollowupVo.patientInfo patientInfo : patientInfo4) {
                                QueryDoctorFollowupResp.patientInfo pi = new QueryDoctorFollowupResp.patientInfo();
                                BeanUtils.copy(patientInfo, pi);
                                patientInfoList4.add(pi);
                            }
                            //时间升序
                            Collections.sort(patientInfoList4, (Comparator<QueryDoctorFollowupResp.patientInfo>) (o1,
                                                                                                                  o2) -> {
                                Date date1 = o1.getTime();
                                Date date2 = o2.getTime();
                                if (CommonUtils.isNull(date1) || CommonUtils.isNull(date2)) {
                                    return 0;
                                }
                                return date1.compareTo(date2);
                            });

                            queryDoctorFollowupResp.setMyClinicList(patientInfoList4);
                        }
                    }
                }
                //患者留言
                if (SubscribeTypeEnum.HZLY.getCode().equals(subScriptionType)) {
                    PageQo qo = new PageQo();
                    qo.setPageSize(Constants.INTERVAL_TIME);
                    try {
                        SimplePageInfo<NewReplyListVO> simplePageInfo = healthInfoRpcService.getNewReplyList(qo);
                        List<NewReplyListVO> newReplyListVOList = Lists.newArrayList();
                        if (simplePageInfo != null && CommonUtils.isNotEmpty(simplePageInfo.getList())) {
                            newReplyListVOList = simplePageInfo.getList();
                        }
                        queryDoctorFollowupResp.setPatientMessageList(newReplyListVOList);
                    } catch (ControllerException e) {
                        logger.info("查询健康咨询失败", e.getMessage());
                    }
                }
                //病历订阅
                if (SubscribeTypeEnum.BLDY.getCode().equals(subScriptionType)) {
                    String userId = null;
                    try {
                        userId = doctorInfoRpcService.getDoctorUserId(request.getDocId());
                    } catch (Throwable throwable) {
                        logger.info("获取医生用户标识失败", throwable.getMessage());
                    }
                    List<ListSubscribeResponse> subscribeResponses = patientSearchRuleDAO.listSubscribe(userId);
                    List<QueryDoctorFollowupResp.patientInfo> patientInfoList6 = Lists.newArrayList();
                    if (CommonUtils.isNotEmpty(subscribeResponses)) {
                        for (ListSubscribeResponse subscribeResponse : subscribeResponses) {
                            QueryDoctorFollowupResp.patientInfo patientInfo6 = new QueryDoctorFollowupResp.patientInfo();
                            patientInfo6.setDiseaseName(subscribeResponse.getRuleName());
                            patientInfo6.setUnReadNumber(subscribeResponse.getUnreadCount());
                            patientInfoList6.add(patientInfo6);
                        }
                    }
                    queryDoctorFollowupResp.setSubscribeDiseaseList(patientInfoList6);
                }
            }
        }
        return queryDoctorFollowupResp;
    }

    /**
     * 查询我的科室
     *
     * @param request
     * @return
     */
    @RpcService
    public QueryDoctorDepartmentResp queryDepartmentList(QueryDoctorFollowupReq request) throws ControllerException {
        QueryDoctorDepartmentResp queryDoctorDepartmentResp = new QueryDoctorDepartmentResp();
        if (CommonUtils.isEmpty(request.getDocId())) {
            throw new ControllerException(ResultCode.ERROR, "入参不能为空");
        }
        try {
            logger.info("查询我的科室request" + JSONUtils.toString(request));

            List<QueryDoctorDepartmentListResponse> departmentList = docTeamRpcService.queryDoctorDepartmentList(request.getDocId());
            queryDoctorDepartmentResp.setDepartmentList(departmentList);
            return queryDoctorDepartmentResp;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("查询我的科室失败：" + e.getMessage());
            throw new ControllerException(ResultCode.PARAMETERS_EMPTY, "查询我的科室失败：" + e.getMessage());
        }
    }

    /**
     * 编辑我的订阅模块
     *
     * @param request
     * @return
     */
    @RpcService
    public void editMySubScriptionType(QueryDoctorFollowupReq request) throws ControllerException {
        try {
            logger.info("编辑我的订阅模块request" + JSONUtils.toString(request));
            if (CommonUtils.isEmpty(request.getOrganizationId()) || CommonUtils.isEmpty(request.getDepartmentId()) || CommonUtils.isEmpty(request.getDoctorId())) {
                throw new ControllerException(ResultCode.ERROR, "入参不能为空");
            }

            Date now = new Date();
            //先查询是否已存在专科随访模块订阅记录，存在修改，不存在则新增
            Long count = followUpSubsmoduleDao.getMySubScriptionTypeCount(request.getOrganizationId(), request.getDepartmentId(), request.getDoctorId());
            if (count > 0) {//修改
                followUpSubsmoduleDao.updateMySubScriptionType(now, request.getSubScriptionType(), request.getOrganizationId(), request.getDepartmentId(), request.getDoctorId());
            } else {//新增
                FollowUpSubsmoduleEntity recode = new FollowUpSubsmoduleEntity();
                recode.setModuleCode(FollowUpSubsmoduleEnum.FOLWMODEL.getModuleCode());
                recode.setModuleName(FollowUpSubsmoduleEnum.FOLWMODEL.getModuleName());
                recode.setOrganizationId(request.getOrganizationId());
                recode.setDepartmentId(request.getDepartmentId());
                recode.setDoctorId(request.getDoctorId());
                recode.setSubScriptionType(request.getSubScriptionType());
                recode.setCreateDt(now);
                recode.setLastModifyDt(now);
                recode.setIsEnable("1");
                followUpSubsmoduleDao.save(recode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("编辑我的订阅模块失败：" + e.getMessage());
            throw new ControllerException(ResultCode.PARAMETERS_EMPTY, "编辑我的订阅模块失败：" + e.getMessage());
        }
    }

    /**
     * 查询我的订阅模块
     *
     * @param request
     * @return
     */
    @RpcService
    public FollowUpSubsmoduleResp qryMySubScriptionType(QueryDoctorFollowupReq request) throws ControllerException {
        logger.info("查询我的订阅模块request" + JSONUtils.toString(request));
        if (CommonUtils.isEmpty(request.getOrganizationId()) || CommonUtils.isEmpty(request.getDoctorId())) {
            throw new ControllerException(ResultCode.ERROR, "入参不能为空");
        }
        try {
            FollowUpSubsmoduleResp followUpSubsmoduleResp = new FollowUpSubsmoduleResp();
            followUpSubsmoduleResp.setSubScriptionType(followUpSubsmoduleDao.qryMySubScriptionType(request));
            return followUpSubsmoduleResp;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("查询我的订阅模块失败：" + e.getMessage());
            throw new ControllerException(ResultCode.PARAMETERS_EMPTY, "查询我的订阅模块失败：" + e.getMessage());
        }
    }

    /**
     * @Author:FangZhiYi
     * @Description 患者上传门诊复诊病历
     * @Params [recordsReq]
     * @Return java.lang.String
     * @Data Created in 2021/10/21 10:33
     * @Moddified By:
     */
    @RpcService
    public JSONObject uploadOutpatientRecords(UploadOutpatientRecordsReq recordsReq) throws ControllerException {
        FollowUpRecords followUpRecords = followUpRecordsDAO.get(recordsReq.getRecordId());
        if (null == followUpRecords) {
            throw new ControllerException("随访记录不存在，无法上传院外复诊病历");
        }
        //调取答案上传接口
        String url = SpringPropertiesUtil.get("editor_follow_up") + "/api/auth/editorAnswer/save";
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(recordsReq));
        JSONObject result = HttpClientUtils.doPostJSONRequest(url, jsonParams);
        int code = result.getInteger("code");
        if (code == ResultCode.SUCCESS) {
            //更新随访记录状态
            followUpRecords.setFollowUpStatus((byte) 2);
            followUpRecords.setMedicalRecordUploadFlag((byte) 1);
            followUpRecordsDAO.update(followUpRecords);
            JSONObject data = result.getJSONObject("data");

            //生成下一次随访计划
            followUpPlanService.createNextFollowUpRecords(followUpRecords);
            return data;
        } else {
            throw new ControllerException("表单答案提交失败：" + result.getString("message"));
        }
    }

    /**
     * 更改慢病管理复诊预约-随访记录状态为 已预约
     *
     * @param recordId
     */
    @RpcService
    public void updateFollowUpStatusById(Long recordId) {
        try {
            followUpRecordsDAO.updateFollowUpStastusById(Byte.valueOf(Constants.TWO_STRING), recordId);
        } catch (Throwable throwable) {
            logger.info("修改状态失败");
        }
    }


    /**
     * 居民-我的院后随访计划
     *
     * @param request
     * @return
     */
    @RpcService
    public QueryPlanListResponse queryFusAfterPlanList(QueryPlanListRequest request) throws ControllerException {

        QueryPlanListResponse response = new QueryPlanListResponse();
        String today = DateUtils.dateFormate(new Date(), "yyyy-MM-dd");
        if (CommonUtils.isEmpty(request.getCardType()) || CommonUtils.isEmpty(request.getCardNumber())) {
            throw new ControllerException(ResultCode.ERROR, "入参不能为空");
        }

        List<FusAfterHosRecord> recordList = fusAfterHosRecordDAO.queryRecordsByPerson(request.getCardType(), request.getCardNumber(), 0, 1);

        if (CommonUtils.isNotEmpty(recordList)) {
            BeanUtils.copy(recordList.get(0), response);
        }
        List<FusAfterHosRecord> dateGroupList = fusAfterHosRecordDAO.queryDateGroupList(request.getCardType(), request.getCardNumber(), today);
        if (CommonUtils.isEmpty(dateGroupList)) {
            return response;
        }
        List<QueryPlanListResponse.dateGroup> resDateGroupList = Lists.newArrayList();

        for (FusAfterHosRecord fusAfterHosRecord : dateGroupList) {
            QueryPlanListResponse.dateGroup resDateGroup = new QueryPlanListResponse.dateGroup();
            resDateGroup.setPlanDate(fusAfterHosRecord.getPlanTime());
            resDateGroupList.add(resDateGroup);
            List<QueryPlanListResponse.FusAfterDatePlan> fusAfterDatePlanList = fusAfterHosRecordDAO.queryPlanList(request.getCardType(), request.getCardNumber(), fusAfterHosRecord.getPlanTime());

            if (CommonUtils.isEmpty(fusAfterDatePlanList)) {
                continue;
            }
            resDateGroup.setFusAfterDatePlanList(fusAfterDatePlanList);

            for (QueryPlanListResponse.FusAfterDatePlan fusAfterDatePlan : fusAfterDatePlanList) {
                Organization organization = organizationRpcService.getOrgDetailByOrgCode(fusAfterDatePlan.getOrganizationId());
                if (organization != null) {
                    fusAfterDatePlan.setOrgId(organization.getOrgId());
                    fusAfterDatePlan.setOrganizationName(organization.getFullName());
                    Dept dept = deptMainRpcService.getDeptByLocalDeptId(organization.getOrgId(), fusAfterDatePlan.getDepartmentId());
                    if (dept != null) {
                        fusAfterDatePlan.setDeptId(dept.getDeptId());
                    }
                }

                //填充随访问卷表单
                List<FusAfterRequisitionRecord> fusAfterRequisitionList = fusAfterRequisitionRecordDAO.findQuestionByRecordId(fusAfterDatePlan.getRecordId());
                fusAfterDatePlan.setQuestionnaireList(fusAfterRequisitionList);
                if (CommonUtils.isNotEmpty(fusAfterRequisitionList)) {
                    fusAfterRequisitionList.stream().forEach(requisition -> {
                        if (CommonUtils.isNotEmpty(requisition.getQuestionnaireName())) {
                            requisition.setQuestionnaireName(requisition.getQuestionnaireName().replace("<p>", "").replace("</p>", "").replace("<br>", ""));
                        }
                    });
                }

                List<FusAfterRecordsContentResp> contentRespList = new ArrayList<>();

                //健康宣教
                List<FusAfterHealthEducation> fusAfterHealthEducations = fusAfterHealthEducationDAO.queryHealthEducationByRecordId(fusAfterDatePlan.getRecordId());
                fusAfterDatePlan.setFusAfterHealthEducationList(fusAfterHealthEducations);
                if (CommonUtils.isNotEmpty(fusAfterHealthEducations)){
                    fusAfterHealthEducations.stream().forEach(e->{
                        FusAfterRecordsContentResp contentResp = new FusAfterRecordsContentResp();
                        BeanUtils.copy(e,contentResp);
                        contentResp.setFollowUpRecordsContentId(e.getId());
                        contentRespList.add(contentResp);

                    });
                }

                //门诊复诊类型  -----复诊项目
                List<FusAfterHosRecordContent> fusAfterHosRecordContents = fusAfterHosRecordContentDAO.queryContentByRecordId(fusAfterDatePlan.getRecordId());
                fusAfterDatePlan.setFusAfterHosRecordContentList(fusAfterHosRecordContents);
                if (CommonUtils.isNotEmpty(fusAfterHosRecordContents)){
                    fusAfterHosRecordContents.stream().forEach(f->{
                        FusAfterRecordsContentResp contentResp = new FusAfterRecordsContentResp();
                        BeanUtils.copy(f,contentResp);
                        contentResp.setFollowUpRecordsContentId(f.getId());
                        contentRespList.add(contentResp);
                    });
                }

                //返回推荐科室
                List<FusAfterRecommendDept> fusAfterRecommendDepts = fusAfterRecommendDeptDAO.queryByRecordId(fusAfterDatePlan.getRecordId());
                fusAfterDatePlan.setRecommendDept(fusAfterRecommendDepts);

                fusAfterDatePlan.setFollowUpPlanList(contentRespList);
            }

        }
        response.setDateGroupList(resDateGroupList);
        return response;
    }


    /**
     * 居民-院后随访  我的宣教
     *
     * @param request
     * @return
     */
    @RpcService
    public List<DiseasesAndFusListResponse> queryFusAfterEducation(QueryPlanListRequest request) throws ControllerException {


        if (CommonUtils.isEmpty(request.getCardType()) || CommonUtils.isEmpty(request.getCardNumber())) {
            throw new ControllerException(ResultCode.ERROR, "入参不能为空");
        }

        List<DiseasesAndFusListResponse> educationList = fusAfterHosRecordDAO.queryEducationList(request);
        if (CommonUtils.isEmpty(educationList)){
            return new ArrayList<>();
        }

        educationList.stream().forEach(e->{
            //获取病种列表
            try {
                List<FusHealthEducationRelation> fusHealthEducationRelations = fusHealthEducationService.findFusHealthEducationRelations(Long.valueOf(e.getEducationId()));
                e.setFusHealthEducationRelationLists(fusHealthEducationRelations);
            } catch (ControllerException e1) {
                e1.printStackTrace();
            }

        });
        return educationList;

    }
}